package com.tpvlog.im.gateway.tcp.common;

import com.tpvlog.im.common.Request;
import com.tpvlog.im.common.Response;
import com.tpvlog.im.gateway.tcp.dispatcher.DispatcherInstance;
import com.tpvlog.im.gateway.tcp.dispatcher.DispatcherInstanceManager;
import com.tpvlog.im.protocal.AuthenticateRequestProto;
import io.netty.channel.socket.SocketChannel;

/**
 * 请求处理组件
 */
public class RequestHandler {

    private RequestHandler() {
    }

    public static RequestHandler getInstance() {
        return RequestHandlerHolder.INSTANCE;
    }

    /**
     * 认证请求处理
     *
     * @return
     */
    public void authenticate(AuthenticateRequestProto.AuthenticateRequest authenticateRequest) {
        // 1.选择一个Dispatcher实例
        DispatcherInstanceManager dispatcherInstanceManager = DispatcherInstanceManager.getInstance();
        DispatcherInstance dispatcherInstance = dispatcherInstanceManager.chooseDispatcherInstance();

        // 2.发送请求
        dispatcherInstance.authenticate(authenticateRequest);
        System.out.println("向随机挑选的分发系统（地址为：" + dispatcherInstance.getSocketChannel() + "）发送请求，" +
                "请求大小为：" + authenticateRequest.toByteArray().length);

    }

    public void sendMessage(Request request) {
        // 1.选择一个Dispatcher实例
        DispatcherInstanceManager dispatcherInstanceManager = DispatcherInstanceManager.getInstance();
        DispatcherInstance dispatcherInstance = dispatcherInstanceManager.chooseDispatcherInstance();

        // 2.发送请求
        dispatcherInstance.sendMessage(request);
        System.out.println("向随机挑选的分发系统（地址为：" + dispatcherInstance.getSocketChannel() + "）发送单聊消息请求");
    }

    /**
     * 发送消息推送的响应
     *
     * @param response
     */
    public void pushMessageResponse(Response response) {
        // 1.选择一个Dispatcher实例
        DispatcherInstanceManager dispatcherInstanceManager = DispatcherInstanceManager.getInstance();
        DispatcherInstance dispatcherInstance = dispatcherInstanceManager.chooseDispatcherInstance();

        // 2.发送响应
        dispatcherInstance.pushMessageResponse(response);
        System.out.println("向随机挑选的分发系统（" +
                "地址为：" + dispatcherInstance.getSocketChannel() + "）发送消息推送的响应");
    }

    private static class RequestHandlerHolder {
        private static final RequestHandler INSTANCE = new RequestHandler();
    }


}
